package com.example.demo.Controller;

import com.example.demo.Service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadController {

    @Autowired
    private ResumeService resumeService;

    @PostMapping("/updateAvatar/{id}")
    public String updateAvatar(@PathVariable("id") Long id,
                               @RequestParam("file") MultipartFile file,
                               Model model) throws IOException {
        if (file.isEmpty()) {
            model.addAttribute("error", "上传失败：文件为空");
            return "redirect:/resume/" + id;
        }

        // 获取简短随机文件名 + 后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
        String shortUUID = UUID.randomUUID().toString().substring(0, 8);
        String fileName = shortUUID + suffix;

        // 上传到项目根目录下的 uploads/images
        String uploadDir = new File("uploads/images").getAbsolutePath();
        new File(uploadDir).mkdirs(); // 自动创建目录（如果不存在）

        File dest = new File(uploadDir, fileName);
        file.transferTo(dest);

        // 更新数据库中的头像文件名
        resumeService.updateavatar(fileName, id);

        return "redirect:/resume/" + id;
    }
}
